<?php

class MembersController extends AdminController
{
  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  public function filters()
  {
    return array(
      'accessControl',
    );
  }

  public function accessRules()
  {
    return array(
      array('allow',
        'actions'=>array('list', 'create', 'update','delete'),
        'roles'=>array('admin'),
      ),
      array('allow',
        'actions'=>array('update'),
        'roles'=>array('member'),
      ),
      array('deny',
        'users'=>array('*'),
      ),
    );
  }

  public function actionCreate()
  {
    $model=new Members;

    if(isset($_POST['Members']))
    {
      $model->attributes=$_POST['Members'];
      $model->password = sha1($model->password . $model->nickname . Constants::SALT);

      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Tạo Member thành công");
        $this->redirect(array('list'));
      }
    }

    $this->render('create',array(
      'model'=>$model,
      'memberTypes' => Constants::getMemberType(),
      'statusList' => Constants::getMemberStatus(),
    ));
  }

  public function actionUpdate($id = null)
  {
    if (!Constants::isAdmin()) {
      $model=$this->loadModel(Yii::app()->user->id);
    } else {
        if ($id) {
            $model=$this->loadModel($id);
        } else {
            $model=$this->loadModel(Yii::app()->user->id);
        }
    }

    if(isset($_POST['Members']))
    {
      $model->attributes=$_POST['Members'];
      $model->password = sha1($model->password . $model->nickname . Constants::SALT);

      if (!Constants::isAdmin()) {
        $model->member_type = Constants::MEMBER_TYPE_USER;
      }

      if ($model->save()) {
        Yii::app()->user->setFlash('success', "Cập nhật Members thành công");
        $this->redirect(array('list') + $_GET);
      }
    }

    $model->password = "";

    $this->render('update',array(
      'model'=>$model,
      'memberTypes' => Constants::getMemberType(),
      'statusList' => Constants::getMemberStatus(),
    ));
  }

  public function actionDelete($id)
  {
    $this->loadModel($id)->delete();

      if (!isset($_GET['ajax'])) {
      Yii::app()->user->setFlash('success', "Xóa Member thành công");
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
    }
  }

  public function actionList()
  {
    $criteria = new CDbCriteria();

    $criteria->addCondition('status =:status', 'AND');
    $params = array(':status' => Constants::STATUS_ACTIVE);
    $searchData = array();

    if (isset($_GET['Members']) && sizeof($_GET['Members']) > 0) {
      $searchData = $_GET['Members'];

      foreach ($searchData as $key => $val) {
        if ($val != '') {
          $param = ':' . $key;
          $condtion = '';

          if ($key != 'create_date') {
            $condtion = $key . ' LIKE :' . $key . '';
            $params[$param] = '%' . $val . '%';
          } else {
            $condtion = $key . ' = :' . $key . '';
            $params[$param] = $val;
          }

          $criteria->addCondition($condtion, 'AND');
        }
      }
    }

    $criteria->params = $params;
    $count = Members::model()->count($criteria);

    $pages = new CPagination($count);

    // results per page
    $pages->pageSize = Constants::RECORD_OF_PAGE;
    $pages->applyLimit($criteria);

    $criteria->order = 'member_id DESC';
    $sort = new ExtSort('Members');
    $sort->applyOrder($criteria);

    $models = Members::model()->findAll($criteria);
    $searchModel=new Members('search');

    $this->render('list', array('models' => $models, 
                    'pages' => $pages,
                    'sort' => $sort,
                    'searchModel' => $searchModel,
                    'searchData' => $searchData,
                    'statusList' => Constants::getMemberStatus(),
                    'memberTypes' => Constants::getMemberType()));
  }

  public function loadModel($id)
  {
    $model=Members::model()->findByPk($id);
    if($model===null)
      throw new CHttpException(404,'The requested page does not exist.');
    return $model;
  }

  protected function performAjaxValidation($model)
  {
    if(isset($_POST['ajax']) && $_POST['ajax']==='members-form')
    {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }
  }
}
